﻿//#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
//
#include "opencv2/opencv.hpp"


using namespace std;
using namespace cv;

const unsigned int cameraID = 0;

int main() {
	//define chess-board variables
	int iNumBoards = 10; //how many successful boards to collect
	int iNumCornersHorizontal = 8;//7
	int iNumCornersVertical = 6;//5
	//get input of chess-board info from users
	double disConersHori=18.75;
	double disConersVer=18.75;

	//setup more variables
	int iNumSquares = iNumCornersHorizontal * iNumCornersVertical;
	Size sBoardSize = Size(iNumCornersHorizontal, iNumCornersVertical);

	//setup video capture
	VideoCapture capture = VideoCapture(cameraID);
	if(!capture.isOpened()) {
		printf("camera %d open failed \n", cameraID);
		return -1;
	}

	/*
	 * important: setup object points and image points
	 */
	vector< vector<Point2f> > imagePoints;
	vector< vector<Point3f> > objectPoints;
	//setup corners
	vector<Point2f> corners;
	vector<Point3f> obj;

	int successes = 0;

	//setup image
	Mat image;
	Mat gray_image;
	capture >> image;

	//setup view win
	namedWindow("win1",1);
	namedWindow("win2", 1);
	
	//setup init obj points
	for(int j = 0; j < iNumSquares; j++){
		obj.push_back(Point3f(j/iNumCornersHorizontal*disConersHori,
				j%iNumCornersHorizontal*disConersVer,
				0.0f));
		//print points
		
		printf("Object[%d]->Point3f(%d, %d, 0)\n",
				j,
				j/iNumCornersHorizontal,
				j%iNumCornersHorizontal);
	}

	//main loop - checking chessboards
	while(successes < iNumBoards){
		capture >> image;
		cvtColor(image, gray_image, CV_BGR2GRAY, 0);

		bool found = findChessboardCorners(image,
				sBoardSize,
				corners,
				CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
		if(found){
			cornerSubPix(gray_image,
					corners,
					Size(11, 11),
					Size(-1, -1),
					TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1)
					);
			drawChessboardCorners(image, sBoardSize, corners, found);
		}
		
		//keyboard event listener
		int key = waitKey(10);
	
		if(key == 32 && found){ //32 is the spacebar key
			bitwise_not(image, image); //to blink
			
			successes ++;
			//
			imagePoints.push_back(corners);
			objectPoints.push_back(obj);
			printf("Got Chessboard Snap %d/%d \n",
					successes,
					iNumBoards);
			//
			if(successes >= iNumBoards){
				printf("Captured ALL successful snaps, exiting... \n");
				break;
			}
			
		}
		
		//show img
		imshow("win1", image);
		imshow("win2", gray_image);
	}
	
			
	//release resource
	capture.release();
	return 0;
}